package UDP.UDP6;

import com.sun.org.apache.xerces.internal.impl.xs.SchemaNamespaceSupport;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class UdpClient {

    private DatagramSocket socket;
    private String serverIp;
    private int port;

    public UdpClient(String serverIp, int port) throws SocketException {
        this.socket = new DatagramSocket();
        this.serverIp = serverIp;
        this.port = port;
    }

    public void start() throws IOException {
        Scanner in = new Scanner(System.in);
        while(true) {
            //1.输入请求
            System.out.print("->");
            String request = in.next();
            //2.封装请求并发送给服务器
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(), request.getBytes().length,
                    InetAddress.getByName(this.serverIp), port);
            socket.send(requestPacket);
            //3.接收服务器响应并解析
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096], 4096);
            socket.receive(responsePacket);
            String response = new String(responsePacket.getData(), 0, responsePacket.getLength());
            //4.打印响应
            System.out.println(response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpClient udpClient = new UdpClient("127.0.0.1", 8080);
        udpClient.start();
    }

}
